package com.sxj.shop.filter;

import com.sxj.shop.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 石小俊
 * @date 2024年03月20日 19:57
 */
//@WebFilter("/*")
public class CheckLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取当前进入到过滤器中的请求
        String path = request.getServletPath();
        // 判断该请求是否需要登录
        // 如果是不需要登录的请求则直接放行
        if ("/jsp/login.jsp".equals(path) || "/jsp/register.jsp".equals(path) || "/jsp/main.jsp".equals(path) || "/index.jsp".equals(path) || "/register.user".equals(path) || "/login.user".equals(path) || "/findAll.product".equals(path)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 如果请求需要登录,则判断是否已经登录
        // 如果已经登录了,则session会保存对应的用户信息
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            // 如果没有取到,说明尚未登录
            request.setAttribute("loginMsg", "请先登录!");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
            return;
        }
        // 如果取到了用户信息,则说明已经登录,直接放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
